package com.xjscrm.console.service.customer.wwCustomer.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerCustomerDelMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.RepeatWwCustomer;
import com.xjscrm.common.entity.RepeatWwCustomerLog;
import com.xjscrm.common.entity.WwCustomer;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.list.WwCustomerListQuery;
import com.xjscrm.console.param.wwCustomer.*;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerDistinctService;
import com.xjscrm.console.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class WwCustomerDistinctServiceImpl implements WwCustomerDistinctService {

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private RepeatWwCustomerMapper repeatWwCustomerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RepeatWwCustomerLogMapper repeatWwCustomerLogMapper;

    @Autowired
    private WhiteListMapper whiteListMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Override
    @Async("taskExecutor")
    public void checkRepeatWwCustomer(CheckRepeatWwCustomerDto checkRepeatWwCustomerDto) {
        if(checkRepeatWwCustomerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(checkRepeatWwCustomerDto.getDeviceUniqueIds()==null&&checkRepeatWwCustomerDto.getDeviceUniqueIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(checkRepeatWwCustomerDto.getDeviceUniqueIds().size()<2){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "至少选择两个机器人");
        }

        //删除上次的检测标识
        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),checkRepeatWwCustomerDto.getMerId());
        if(redisTemplate.hasKey(redisKey)){
            redisTemplate.delete(redisKey);
        }


        Long falg = IdWorker.getId();
        //设置取消标识
        String key=String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_BREAK_FALG.getKey(),checkRepeatWwCustomerDto.getMerId());
        redisTemplate.opsForValue().set(key,falg);


        CustomerQuery customerQuery=new CustomerQuery();
        Long idStart = 0L;
        customerQuery.setMerId(checkRepeatWwCustomerDto.getMerId());
        customerQuery.setAsc(true);
        customerQuery.setCurrent(1);
        customerQuery.setSize(10);
        customerQuery.setOrderByField("id");
        customerQuery.setIdStart(idStart);
        String orderBy = OrderByUtil.getOrderBy(customerQuery.getOrderByField(), customerQuery.isAsc());
        PageHelper.startPage(customerQuery.getCurrent(),customerQuery.getSize(),orderBy);
        List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);
        while (customerVoList!=null&&!customerVoList.isEmpty()){
            //暂停，删除该key 终止任务
            if(!redisTemplate.hasKey(key)){
                 return;
            }


            for (WwCustomerVo wwCustomerVo:customerVoList) {
                try {
                    if(wwCustomerVo.getId().longValue() > idStart.longValue()){
                        idStart = wwCustomerVo.getId();
                    }
                    //检测每个用户是否同时存在多个机器人，存在的用户返回
                    WwCustomer wwCustomer = containDeviceJudge(wwCustomerVo, checkRepeatWwCustomerDto.getDeviceUniqueIds());

                    //查询是否要忽略白名单 要则在白名单中忽略
                    if(checkRepeatWwCustomerDto.getIgnoreWhiteList()!=null&&checkRepeatWwCustomerDto.getIgnoreWhiteList()==1){
                        WwCustomerListQuery wwCustomerListQuery=new WwCustomerListQuery();
                        wwCustomerListQuery.setMerId(checkRepeatWwCustomerDto.getMerId());
                        wwCustomerListQuery.setWxid(wwCustomer.getWxid());
                        List<WwCustomerWhiteVo> whiteList = whiteListMapper.getWhiteList(wwCustomerListQuery);
                        if(whiteList!=null&&!whiteList.isEmpty()){
                          break;
                        }
                          //忽略企业号
                        if(!StringUtils.isBlank(wwCustomer.getCorpId())){
                          break;
                        }
                    }

                    if(wwCustomer!=null){
                        //将需要去重的用户放入去重表
                        addRepeatWwCustomer(wwCustomer, checkRepeatWwCustomerDto.getMerId(),falg);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            customerQuery.setIdStart(idStart);
            PageHelper.startPage(customerQuery.getCurrent(), customerQuery.getSize(), orderBy);
            customerVoList =  wwCustomerMapper.getCustomer(customerQuery);
        }



        //插入记录表

            int time = DateUtil.getTime();
            RepeatWwCustomerLog repeatWwCustomerLog=new RepeatWwCustomerLog();
            repeatWwCustomerLog.setId(falg);
            repeatWwCustomerLog.setMerId(checkRepeatWwCustomerDto.getMerId());
            if(checkRepeatWwCustomerDto.getOperatorType()==0){
                repeatWwCustomerLog.setUserId(checkRepeatWwCustomerDto.getMerId());
                repeatWwCustomerLog.setOperateType(0);
            }
            if(checkRepeatWwCustomerDto.getOperatorType()==1){
                repeatWwCustomerLog.setUserId(checkRepeatWwCustomerDto.getChildId());
                repeatWwCustomerLog.setOperateType(1);
            }
                repeatWwCustomerLog.setRepeatNum(0);

               int totalByFalg = repeatWwCustomerMapper.getTotalByFalg(checkRepeatWwCustomerDto.getMerId(), falg);
                repeatWwCustomerLog.setTotalNum(totalByFalg);
                repeatWwCustomerLog.setCreateTime(time);
                repeatWwCustomerLog.setUpdateTime(time);
                repeatWwCustomerLogMapper.insertRepeatWwCustomerLog(repeatWwCustomerLog);

            String redisCacheKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),checkRepeatWwCustomerDto.getMerId());
            redisTemplate.opsForValue().set(redisCacheKey,falg);

    }



    private WwCustomer containDeviceJudge(WwCustomerVo wwCustomerVo, List<Long> deviceUniqueIds) {
        if(wwCustomerVo==null){
            return null;
        }
        WwCustomer wwCustomer=new WwCustomer();
        WwCustomer wwCustomerResult = new WwCustomer();
        Integer falg=0;
        for (Long deviceUniqueId:deviceUniqueIds) {
            wwCustomer= wwCustomerMapper.getByDeviceAndWxid(wwCustomerVo.getWxid(),deviceUniqueId,wwCustomerVo.getMerId());
           if(wwCustomer!=null){
               falg++;
               wwCustomerResult=wwCustomer;
           }
        }
        if(falg<2){
            return null;
        }
        return wwCustomerResult;

    }

    private void addRepeatWwCustomer(WwCustomer wwCustomer, Long merId, long falg) {
        if(wwCustomer==null){
            return ;
        }

          try {
              List<RepeatDevice> repeatDeviceList=new ArrayList<>();
              List<Long> deviceUniqueIds=new ArrayList<>();
              //获取当前客户的所有机器人
              CustomerQuery customerQuery=new CustomerQuery();
              customerQuery.setMerId(merId);
              customerQuery.setWxid(wwCustomer.getWxid());
              List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);
              if(customerVoList!=null&&!customerVoList.isEmpty()){
                  deviceUniqueIds = customerVoList.stream().map(WwCustomerVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
              }
              if(deviceUniqueIds!=null&&!deviceUniqueIds.isEmpty()){
                  //获取机器人信息
                  WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                  wwDeviceQuery.setMerId(merId);
                  wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                  List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                  if (wwDeviceVoList!=null&&!wwDeviceVoList.isEmpty()){
                      for (WwDeviceVo wwDeviceVo:wwDeviceVoList) {
                          RepeatDevice repeatDevice = new RepeatDevice();
                           repeatDevice.setMerId(wwDeviceVo.getMerId());
                           repeatDevice.setDeviceUniqueId(wwDeviceVo.getId());
                           repeatDevice.setDeviceName(wwDeviceVo.getDeviceName());
                           repeatDevice.setDeviceHeaderImage(wwDeviceVo.getHeadImgUrl());
                          repeatDevice.setStatus(0);
                           repeatDeviceList.add(repeatDevice);
                      }
                  }
              }

              RepeatWwCustomerDto repeatWwCustomerDto=new RepeatWwCustomerDto();
              repeatWwCustomerDto.setWxid(wwCustomer.getWxid());
              repeatWwCustomerDto.setMerId(wwCustomer.getMerId());
              repeatWwCustomerDto.setCustomerName(wwCustomer.getName());
              repeatWwCustomerDto.setCustomerHeaderImage(wwCustomer.getHeadImgUrl());
              if(repeatDeviceList!=null&&!repeatDeviceList.isEmpty()){
                  repeatWwCustomerDto.setDeviceData(repeatDeviceList);
              }
              repeatWwCustomerDto.setFalg(falg);
              RepeatWwCustomer repeatWwCustomer = new RepeatWwCustomer();
              BeanUtil.copyProperties(repeatWwCustomerDto,repeatWwCustomer,"deviceData");
              repeatWwCustomer.setDeviceData(JSONObject.toJSONString(repeatWwCustomerDto.getDeviceData()));
              repeatWwCustomerMapper.addRepeatWwCustomer(repeatWwCustomer);
          }catch (Exception e){
              e.printStackTrace();
          }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void breakCheck(BaseDto baseDto) {
        if(baseDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String key=String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_BREAK_FALG.getKey(),baseDto.getMerId());
        if(redisTemplate.hasKey(key)){
            Long falg = (Long) redisTemplate.opsForValue().get(key);

            //查看已经插入的去重客户 s删除
            RepeatWwCustomerQuery repeatWwCustomerQuery=new RepeatWwCustomerQuery();
            repeatWwCustomerQuery.setMerId(baseDto.getMerId());
            repeatWwCustomerQuery.setFalg(falg);
            List<RepeatWwCustomerVo> repeatWwCustomerVoList=repeatWwCustomerMapper.RepeatWwCustomerList(repeatWwCustomerQuery);
            if(repeatWwCustomerVoList!=null&&!repeatWwCustomerVoList.isEmpty()){
                repeatWwCustomerVoList.forEach(it->repeatWwCustomerMapper.deleById(it.getId(),it.getMerId()));
            }

            //查询已有的记录 删除
            RepeatWwCustomerLog repeatWwCustomerLog= repeatWwCustomerLogMapper.getById(falg,baseDto.getMerId());
            if(repeatWwCustomerLog!=null){
                repeatWwCustomerLogMapper.deleById(repeatWwCustomerLog.getId(),repeatWwCustomerLog.getMerId());
            }
            redisTemplate.delete(key);
        }
    }

    @Override
    public Object getCheckStatus(BaseDto baseDto) {
        if(baseDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),baseDto.getMerId());
        if(!redisTemplate.hasKey(redisKey)){
           return false;
        }
        return true;
    }

    @Override
    public Object getCheckResult(RepeatWwCustomerQuery CheckResultQuery) {
        if(CheckResultQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),CheckResultQuery.getMerId());
        if(!redisTemplate.hasKey(redisKey)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "检测记录缺失，请重新检测");
        }
        if(!StringUtils.isBlank(CheckResultQuery.getCustomerKeyWord())){
            CustomerQuery customerQuery=new CustomerQuery();
            customerQuery.setKeyword(CheckResultQuery.getCustomerKeyWord());
            List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
            if(wwCustomerVoList!=null&&!wwCustomerVoList.isEmpty()){
                List<String> collect = wwCustomerVoList.stream().map(WwCustomerVo::getWxid).distinct().collect(Collectors.toList());
                if(collect!=null&&!collect.isEmpty()){
                    CheckResultQuery.setWxids(collect);
                }else {
                    return new MyPageInfo<>(null);
                }
            }else {
                return new MyPageInfo<>(null);
            }
        }

        if(!StringUtils.isBlank(CheckResultQuery.getDeviceKeyWord())){
            WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
            wwDeviceQuery.setMerId(CheckResultQuery.getMerId());
            wwDeviceQuery.setKeyword(CheckResultQuery.getDeviceKeyWord());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                List<Long> collect = wwDeviceList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
                if(collect!=null&&!collect.isEmpty()){
                    CheckResultQuery.setDeviceUniqueIds(collect);
                }else {
                    return new MyPageInfo<>(null);
                }
            }else {
                return new MyPageInfo<>(null);
            }
        }


        Long falg = (Long) redisTemplate.opsForValue().get(redisKey);

        CheckResultQuery.setFalg(falg);
        String orderBy = OrderByUtil.getOrderBy(CheckResultQuery.getOrderByField(), CheckResultQuery.isAsc());
        PageHelper.startPage(CheckResultQuery.getCurrent(),CheckResultQuery.getSize(),orderBy);
        List<RepeatWwCustomerVo> repeatWwCustomerVoList = repeatWwCustomerMapper.RepeatWwCustomerList(CheckResultQuery);
        if(repeatWwCustomerVoList!=null&&!repeatWwCustomerVoList.isEmpty()){
            for (RepeatWwCustomerVo repeatWwCustomerVo:repeatWwCustomerVoList) {
                try {
                    if(!StringUtils.isBlank(repeatWwCustomerVo.getDeviceData())){
                        repeatWwCustomerVo.setRepeatDeviceList(JSONArray.parseArray(repeatWwCustomerVo.getDeviceData(),RepeatDevice.class));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return new MyPageInfo<>(repeatWwCustomerVoList);
    }


    @Override
    public Object deleRepeatWwCustomer(DeleRepeatWwCustomerDto deleRepeatWwCustomerDto) {
        if(deleRepeatWwCustomerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        Integer delNumber=0;
        String delRepeatCusonmNumber=String.format(RedisCacheKeyEnum.DEL_REPEAT_CUSONM_NUMBER.getKey(),deleRepeatWwCustomerDto.getMerId());
        redisTemplate.opsForValue().set(delRepeatCusonmNumber,0);

        if(deleRepeatWwCustomerDto.getRepeatType()==0){
            deleRepeatWwCustomerAll(deleRepeatWwCustomerDto);
        }
        if(deleRepeatWwCustomerDto.getRepeatType()==1){
            deleRepeatWwCustomerBySelect(deleRepeatWwCustomerDto);
        }
        delNumber= (Integer) redisTemplate.opsForValue().get(delRepeatCusonmNumber);
        redisTemplate.delete(delRepeatCusonmNumber);

        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),deleRepeatWwCustomerDto.getMerId());
        if(redisTemplate.hasKey(redisKey)){
            Long falg = (Long) redisTemplate.opsForValue().get(redisKey);
            RepeatWwCustomerLog repeatWwCustomerLog = repeatWwCustomerLogMapper.getById(falg, deleRepeatWwCustomerDto.getMerId());
            repeatWwCustomerLog.setRepeatNum(delNumber);
            repeatWwCustomerLogMapper.update(repeatWwCustomerLog);
        }
        return delNumber;


    }

    private void deleRepeatWwCustomerBySelect(DeleRepeatWwCustomerDto deleRepeatWwCustomerDto) {
        if(deleRepeatWwCustomerDto.getKeepDeivceDto()==null||deleRepeatWwCustomerDto.getKeepDeivceDto().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),deleRepeatWwCustomerDto.getMerId());
        if(!redisTemplate.hasKey(redisKey)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "检测记录缺失，请重新检测");
        }


            for (KeepDeivceDto keepDeivceDto:deleRepeatWwCustomerDto.getKeepDeivceDto()) {
                try {
                    RepeatWwCustomerVo repeatWwCustomerVo  = repeatWwCustomerMapper.getById(keepDeivceDto.getId(), deleRepeatWwCustomerDto.getMerId());
                    if(repeatWwCustomerVo!=null&&!StringUtils.isBlank(repeatWwCustomerVo.getDeviceData())){
                        List<RepeatDevice> repeatDeviceList = JSONArray.parseArray(repeatWwCustomerVo.getDeviceData(), RepeatDevice.class);
                        if(repeatDeviceList!=null&&!repeatDeviceList.isEmpty()){
                            List<RepeatDevice> repeatDevices = keepSelectDevice(repeatDeviceList, repeatWwCustomerVo.getWxid(), repeatWwCustomerVo.getMerId(),keepDeivceDto.getDeviceUniqueIds());
                            if(repeatDevices.stream().anyMatch(it->it.getStatus()==1)){
                                repeatWwCustomerVo.setStatus(1);
                            }
                            repeatWwCustomerVo.setDeviceData(JSONObject.toJSONString(repeatDevices));

                            RepeatWwCustomer repeatWwCustomer=new RepeatWwCustomer();
                            BeanUtil.copyProperties(repeatWwCustomerVo,repeatWwCustomer);
                            repeatWwCustomerMapper.update(repeatWwCustomer);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }


    private List<RepeatDevice> keepSelectDevice(List<RepeatDevice> repeatDeviceList, String wxid, Long merId, List<Long> deviceUniqueIds) {

        List<Long> removedIdList = new ArrayList<>();
        if(deviceUniqueIds==null||deviceUniqueIds.isEmpty()){
            for (RepeatDevice repeatDevice:repeatDeviceList) {
                removedIdList.add(repeatDevice.getDeviceUniqueId());
                repeatDevice.setStatus(1);
            }
        }else {
            for (RepeatDevice repeatDevice:repeatDeviceList) {
                if(deviceUniqueIds.contains(repeatDevice.getDeviceUniqueId())){
                    repeatDevice.setStatus(0);
                }else {
                    removedIdList.add(repeatDevice.getDeviceUniqueId());
                    repeatDevice.setStatus(1);
                }
            }
        }


        //删除客户
        deleCustomer(removedIdList,wxid,merId);

        return repeatDeviceList;

    }

    private void deleRepeatWwCustomerAll(DeleRepeatWwCustomerDto deleRepeatWwCustomerDto) {
        String redisKey= String.format(RedisCacheKeyEnum.DISTINCT_CUSTOMER_WHITCH_FALG.getKey(),deleRepeatWwCustomerDto.getMerId());
        if(!redisTemplate.hasKey(redisKey)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "检测记录缺失，请重新检测");
        }
        if(deleRepeatWwCustomerDto.getKeepDeivceDto()==null||deleRepeatWwCustomerDto.getKeepDeivceDto().isEmpty()){
            Long falg = (Long) redisTemplate.opsForValue().get(redisKey);
            RepeatWwCustomerQuery repeatWwCustomerQuery=new RepeatWwCustomerQuery();
            repeatWwCustomerQuery.setFalg(falg);
            repeatWwCustomerQuery.setMerId(deleRepeatWwCustomerDto.getMerId());
            List<RepeatWwCustomerVo> repeatWwCustomerVoList = repeatWwCustomerMapper.RepeatWwCustomerList(repeatWwCustomerQuery);
            if(repeatWwCustomerVoList!=null&&!repeatWwCustomerVoList.isEmpty()){
                for (RepeatWwCustomerVo repeatWwCustomerVo:repeatWwCustomerVoList) {
                    try {
                        if(!StringUtils.isBlank(repeatWwCustomerVo.getDeviceData())){
                            List<RepeatDevice> repeatDeviceList = JSONArray.parseArray(repeatWwCustomerVo.getDeviceData(), RepeatDevice.class);
                            if(repeatDeviceList!=null&&!repeatDeviceList.isEmpty()){
                                List<RepeatDevice> repeatDevices = keepOneDevice(repeatDeviceList, repeatWwCustomerVo.getWxid(), repeatWwCustomerVo.getMerId());
                                if(repeatDevices.stream().anyMatch(it->it.getStatus()==1)){
                                    repeatWwCustomerVo.setStatus(1);
                                }
                                repeatWwCustomerVo.setDeviceData(JSONObject.toJSONString(repeatDevices));

                                RepeatWwCustomer repeatWwCustomer=new RepeatWwCustomer();
                                BeanUtil.copyProperties(repeatWwCustomerVo,repeatWwCustomer);
                                repeatWwCustomerMapper.update(repeatWwCustomer);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        if(deleRepeatWwCustomerDto.getKeepDeivceDto()!=null||!deleRepeatWwCustomerDto.getKeepDeivceDto().isEmpty()){
            for (KeepDeivceDto keepDeivceDto:deleRepeatWwCustomerDto.getKeepDeivceDto()) {
                try {
                    RepeatWwCustomerVo repeatWwCustomerVo  = repeatWwCustomerMapper.getById(keepDeivceDto.getId(), deleRepeatWwCustomerDto.getMerId());
                    if(repeatWwCustomerVo!=null&&!StringUtils.isBlank(repeatWwCustomerVo.getDeviceData())){
                        List<RepeatDevice> repeatDeviceList = JSONArray.parseArray(repeatWwCustomerVo.getDeviceData(), RepeatDevice.class);
                        if(repeatDeviceList!=null&&!repeatDeviceList.isEmpty()){
                            List<RepeatDevice> repeatDevices = keepOneDevice(repeatDeviceList, repeatWwCustomerVo.getWxid(), repeatWwCustomerVo.getMerId());
                            if(repeatDevices.stream().anyMatch(it->it.getStatus()==1)){
                                repeatWwCustomerVo.setStatus(1);
                            }
                            repeatWwCustomerVo.setDeviceData(JSONObject.toJSONString(repeatDevices));

                            RepeatWwCustomer repeatWwCustomer=new RepeatWwCustomer();
                            BeanUtil.copyProperties(repeatWwCustomerVo,repeatWwCustomer);
                            repeatWwCustomerMapper.update(repeatWwCustomer);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }

    private List<RepeatDevice> keepOneDevice(List<RepeatDevice> repeatDeviceList, String wxid, Long merId) {
        Collections.shuffle(repeatDeviceList,new Random(5));

        RepeatDevice repeatDevice = repeatDeviceList.get(0);
        repeatDevice.setStatus(0);

        List<Long> removedIdList = new ArrayList<>();
        for (int i = 1; i < repeatDeviceList.size(); i++) {
            RepeatDevice device = repeatDeviceList.get(i);
            device.setStatus(1);
            Long id = device.getDeviceUniqueId();
            removedIdList.add(id);
        }

        //删除客户
         deleCustomer(removedIdList,wxid,merId);

        return repeatDeviceList;

    }

    private void deleCustomer(List<Long> removedIdList, String wxid, Long merId) {
        String delRepeatCusonmNumber=String.format(RedisCacheKeyEnum.DEL_REPEAT_CUSONM_NUMBER.getKey(),merId);

        if(removedIdList!=null&&!removedIdList.isEmpty()){
            for (Long deviceUniqueId:removedIdList) {
                WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(wxid, deviceUniqueId, merId);
                if(wwCustomer!=null){
                    wwCustomerMapper.deleById(wwCustomer.getId(),wwCustomer.getMerId());
                    Integer num = (Integer) redisTemplate.opsForValue().get(delRepeatCusonmNumber);
                    redisTemplate.opsForValue().set(delRepeatCusonmNumber,num+1);
                    //发送删除通讯录指令

                    WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), merId);

                    if(wwDevice!=null){
                        MicaTriggerCustomerDelMsg micaTriggerCustomerDelMsg=new MicaTriggerCustomerDelMsg();
                        micaTriggerCustomerDelMsg.setMessageId(wwCustomer.getId());
                        micaTriggerCustomerDelMsg.setWxid(wwCustomer.getWxid());
                        MicaTriggerDto micaTriggerDto= MicaTriggerDto.newInstance(micaTriggerCustomerDelMsg, MicaTriggerType.TRIGGER_CUSTOMER_DEL);
                        micaTriggerDto.setMerId(wwDevice.getMerId());
                        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
                        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
                    }

                }

            }
        }

    }

}
